package gui;

import java.sql.SQLException;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

import DBside.JDBCConnection.Genres;
import LogicSide.ManageSongs;
import LogicSide.Recommendation;
import LogicSide.SongDetails;

public class Recommendations {

	private static String selected_genre;
	private static int num_of_recommendations = 50;
	private static Table recommendedTable;
	private static TableItem selected_item;

	public static Composite createRecommendations(final Shell shell){
		//update 
		Main.inSearch = false;
		final String[] titles = new String[] {"id", "Song", "Album", "Artist", "Year"};
		
		Composite recommendationsComposite = new Composite(shell, SWT.BORDER);
		recommendationsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		recommendationsComposite.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_MAGENTA));
		recommendationsComposite.setLayout(new GridLayout(2, true));
		
		/** RecommedationsComposite will hold three buttons:
		 * 		-Get recommendations
		 * 		-update recommenders
		 * 		-add song
		 * 	A drop-down combo-box to select genre 
		 * 
		 * 	and a table showing the recommendations
		 */
		//Drop-down genre selection
		final Combo genreCombo = new Combo(recommendationsComposite, SWT.READ_ONLY);
		genreCombo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
		fillGenreCombo(genreCombo);
		genreCombo.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				int slected_index = genreCombo.getSelectionIndex();
				selected_genre = genreCombo.getItem(slected_index);
			}
		});
		//
		
		
		// Buttons
		// get recommendations button
		Button getRecommendationsButton = new Button(recommendationsComposite, SWT.PUSH | SWT.FLAT);
		getRecommendationsButton.setText("Get recommendations");
		getRecommendationsButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false, 1, 1));
		getRecommendationsButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				Utils.loadingCursor(Main.display, shell);
				Thread thread = new Thread(new Runnable() {
					
					@Override
					public void run() {
						int genre_id = 9; //default for rock 
						for(Genres genre : Genres.values()){
							if(genre.getName().equals(selected_genre))
								genre_id = genre.getId();
						}
						try {
							final List<SongDetails> recommendations = Recommendation.RecommendSongToMe(genre_id, num_of_recommendations, Main.session);
							System.out.println(recommendations);
							Main.display.asyncExec(new Runnable() {
								
								
								@Override
								public void run() {
									recommendedTable.clearAll();
									recommendedTable.setItemCount(0);
									for(SongDetails sd : recommendations){
										sd.fixNulls();
										TableItem item = new TableItem (recommendedTable, SWT.NONE);
										item.setText(Integer.toString(sd.getSong_id()));
										item.setText(1, sd.getSong_name());
										item.setText(2, sd.getAlbum_name());
										item.setText(3, sd.getArtist_name());
										item.setText(4, Integer.toString(sd.getYear()));
									}
									for (int i = 0; i < titles.length; i++) {
										recommendedTable.getColumn(i).pack();
									}
									Utils.regularCursor(Main.display, shell);
								}
							});
						} catch (SQLException e) {
							Main.display.asyncExec(new Runnable() {
								public void run() {
									Utils.regularCursor(Main.display, shell);
									Utils.popUpFailure(shell);
								}
							});
							
						}
						
					}
				});
				thread.start();
			}
			
		});
		
		// update recommenders
		Button updateRecommendersButton = new Button(recommendationsComposite, SWT.PUSH | SWT.FLAT);
		updateRecommendersButton.setText("Update recommenders");
		updateRecommendersButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false, 1, 1));
		updateRecommendersButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				Utils.loadingCursor(Main.display, shell);
				Thread thread = new Thread(new Runnable() {
					
					@Override
					public void run() {
						try {
							Recommendation.refreshRecommenders(Main.session);
							Main.display.syncExec(new Runnable() {	
								@Override
								public void run() {
									Utils.regularCursor(Main.display, shell);
									Utils.popUpBox("Completed","Done" , shell);
								}
							});
						} catch (SQLException e) {
							Main.display.asyncExec(new Runnable() {
								public void run() {
									Utils.regularCursor(Main.display, shell);
									Utils.popUpFailure(shell);
								}
							});
							
						}
					}
				});
				thread.start();
			}
		});
		
		//add song
		Button addSongButton = new Button(recommendationsComposite, SWT.PUSH | SWT.FLAT);
		addSongButton.setText("Add song");
		addSongButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false, 1, 1));
		addSongButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				if(selected_item != null){
					final int id = Integer.parseInt(selected_item.getText());
					final String name = selected_item.getText(1);
					Utils.loadingCursor(Main.display, shell);
					
					new Thread(new Runnable() {
						public void run() {
							final boolean result = ManageSongs.addSongToUser(id, name, Main.session);
							Main.display.asyncExec(new Runnable() {
								
								@Override
								public void run() {
								if(result){
									Utils.regularCursor(Main.display, shell);
									Utils.popUpBox("Success", "Done", shell);
								}
								else{
									Utils.regularCursor(Main.display, shell);
									Utils.popUpBox("Failure", "Couldn't add song", shell);
								}
								}
							});
						}
					}).start();
				}
				else{
					Utils.popUpBox("Error", "Select a song!", shell);
				}
			}
		});
		//
		
		//Table
		recommendedTable = new Table(recommendationsComposite, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION);
		recommendedTable.setLinesVisible (true);
		recommendedTable.setHeaderVisible (true);
		GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
		data.heightHint = 200;
		data.horizontalSpan = 2;
		recommendedTable.setLayoutData(data);
		recommendedTable.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY));
		
		

		for (int i=0; i<titles.length; i++) {
			TableColumn column = new TableColumn (recommendedTable, SWT.NONE);
			column.setText(titles [i]);
		}	
		
		for (int i=0; i<titles.length; i++) {
			recommendedTable.getColumn(i).pack();
		}
		
		recommendedTable.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				int selected_index = recommendedTable.getSelectionIndex();
				if(selected_index > 0)
					selected_item = recommendedTable.getItem(selected_index);
			}
		});
		//
		
		
		
		return recommendationsComposite;
	}

	public static void fillGenreCombo(Combo genreCombo) {
		for (Genres genre : Genres.values()) {
			genreCombo.add(genre.toString());
		}

	}
}
